import React from 'react';
import PropTypes from 'prop-types';
import postImg from '../../request/post_img';
// 引入scss
import './index.scss';

const E = require('../../../external_module/wangeditor/wangEditor');

class RichEditor extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: '',
    }
    // 初始化一个编辑器
    this.editor = {};
  }
  componentDidMount() {
    this.setEditor();
  }
  setEditor() {
    // 将编辑器对象绑定到本对象
    this.editor = new E('#editor');
    // debug模式
    this.editor.customConfig.debug = true;
    // 编辑框里的内容改变事件
    this.editor.customConfig.onchange = this.props.onChange;
    // 上传图片的服务器地址，此处不是真的地址，设置该属性为了显示从文件上传图片的table card
    this.editor.customConfig.uploadImgServer = '****';
    // 上传图片设置函数
    this.uploadImg();

    this.editor.create();
    // 给编辑器设定默认值
  }
  // 上传图片函数
  setValue(value) {
    this.editor.txt.html(value);
  }
  uploadImg() {
    const _this = this;
    this.editor.customConfig.customUploadImg = function (files, insert) {
      const header = {
        // wp post api 需求
        // 'Content-Disposition': `attachment; filename=${escape(files[0].name)}`,
        // 'Content-Type': 'application/x-www-form-urlencoded',
      };
      // 新建formData
      const formdata = new FormData();
      for (let i = 0; i < files.length; i++) {
        formdata.append('fileImg', files[0]);
      }
      formdata.append('alt_text', _this.props.title);
      formdata.append('title', _this.props.title);
      postImg(formdata, header)
        .then((res) => {
          const json = res.data
          if (json && json.source_url) {
            insert([json.source_url]);
          }
        });
    }
  }
  render() {
    return (
      <div className="rich-editor" id="editor" />
    );
  }
}
export default RichEditor;
RichEditor.propTypes = {
  onChange: PropTypes.func,
}
